package com.chinasoft.controller;

import com.chinasoft.dao.Impl.UserDAOImpl;
import com.chinasoft.dao.UserDAO;
import com.chinasoft.entity.User;
import com.chinasoft.utils.EmailUtils;
import com.chinasoft.utils.MD5Utils;

import java.io.InputStream;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Properties;

/**
 * Created by YE on 2018/5/23.
 */
@WebServlet(name = "EmailServlet", urlPatterns = {"/email"})
public class EmailServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String emailop=request.getParameter("emailop");
        UserDAO userDAO=new UserDAOImpl();
        User user=null;
        Properties p=new Properties();
        PrintWriter out=response.getWriter();
        InputStream is=EmailServlet.class.getResourceAsStream("/url.properties");
        p.load(is);
        if(emailop.equals("send")){
            String username=request.getParameter("username");
            String email=request.getParameter("email");
            user=userDAO.selectUser(username);
            user.setEmail(email);
            StringBuffer link=new StringBuffer();
            link.append("欢迎注册论坛！以下是您的邮箱验证链接：");
            link.append(p.get("baseurl"));
            link.append("email?emailop=verify&uid="+user.getUid()+"&code=");
            String text=user.getUsername()+user.getPassword();
            link.append(MD5Utils.md5(text));
            userDAO.updateEmail(user);
            out.print(EmailUtils.sendEmail(email,link.toString()));
        }
        if(emailop.equals("verify")){
            int uid= Integer.parseInt(request.getParameter("uid"));
            String code=request.getParameter("code");
            user=userDAO.selectUser(uid);
            String text=user.getUsername()+user.getPassword();
            if(code.equals(MD5Utils.md5(text))){
                user.setEmailcheck(1);
            }
            request.getSession().removeAttribute("user");
            request.getSession().setAttribute("user",user);
            if(userDAO.verifyEmail(user)>0){
                out.print("<script>alert('认证成功！');location.href='setting.jsp';</script>");
            }else{
                out.print("<script>alert('认证失败！');location.href='setting.jsp';</script>");
            }
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
